package com.fan.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 313. 超级丑数
 *
 * @author ZhangFan
 * @since 2021/8/9 下午 11:26
 */
public class Question313 {
    public int nthSuperUglyNumber(int n, int[] primes) {
        List<Integer> collect = Arrays.stream(primes).boxed().collect(Collectors.toList());
        int num = 1;
        for (int i = 1, j = 2; i < n; j++) {
            boolean flag = true;
            for (Integer primeFactor : getPrimeFactors(j)) {
                if (!collect.contains(primeFactor)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                num = j;
                i++;
            }
        }
        return num;
    }

    public List<Integer> getPrimeFactors(int num) {
        List<Integer> list = new ArrayList<>();
        List<Integer> factors = getFactors(num);
        for (Integer factor : factors) {
            if (getFactors(factor).size() == 2) {
                list.add(factor);
            }
        }
        return list;
    }

    public List<Integer> getFactors(int num) {
        List<Integer> list = new ArrayList<>();
        for (int i = 1; ; i++) {
            int mod = num % i;
            int j = num / i;
            if (i > j) {
                break;
            }
            if (mod == 0) {
                list.add(i);
                list.add(j);
            }
        }
        return list;
    }
}
